<?

class Search{

var $name="formSearch";
var $tableName;
var $keyName=array("all"=>"All");
var $query;

function initialize($name, $tableName, $key){
	$this->name=$name;
	$this->tableName=$tableName;
	
	if(is_array($key)){
		$this->keyName=array_merge($this->keyName,$key);
	}
}

function getForm(){
	$content="\r <table width=\"409\" border=\"0\"> \r";
  	$content.="\t <tr> \r"; 
    $content.="\t \t <td width=\"69\" class=\"fieldTable\">Find</td>\r";
    $content.="\t \t <td width=\"340\" class=\"fieldTable\"><input name=\"search_$this->name\" type=\"text\" size=\"30\" value=\"".$_GET["search_$this->name"]."\">&nbsp; ";
    $content.="<select name=\"select_$this->name\"> \r";
		$array_key=array_keys($this->keyName);
		$array_value=array_values($this->keyName);
		for($i=0;$i<count($this->keyName);$i++){
			$content.="<option value=\"".base64_encode($array_key[$i]."q2n")."\" ";
			if($_GET["select_$this->name"]==base64_encode($array_key[$i]."q2n"))
				$content.=" selected";
			$content.=">$array_value[$i]</option> \r";
		}
	$content.="\t \t \t </select></td> \r";
    $content.="\t \t <td width=\"66\"><input type=\"submit\" name=\"Search\" value=\"Search\" onclick=\"document.forms[0].action.value='search';document.forms[0].method='GET'\"></td> \r";
  	$content.="\t </tr> \r";
  	$content.="</table> \r";
	
	return $content;
}

function getQuery($query){
	$this->query=trim($query);
	$split_query=split("order by",$query);
	$core_query=trim($split_query[0]);
	$sort_query=(count($split_query)==2?$split_query[1]:"");
	$split_core=split("where",trim($core_query));
	$head_query=trim($split_core[0]);
	$where_query=(count($split_core)>1?trim($split_core[1]):"");
	
	$query_string=ereg_replace("q2n","",base64_decode($_GET["select_$this->name"]));
	
	$array_key=array_keys($this->keyName);
	$array_value=array_values($this->keyName);
	for($i=1;$i<count($this->keyName);$i++){
		$all_where.=$array_key[$i]." like '%".$_GET["search_".$this->name]."%' or ";
	}
	$all_where=substr($all_where,0,strlen($all_where)-3);
	
	if($query_string=="all")
		$where_clause=$all_where;
	else if($_GET["select_$this->name"]!="")
		$where_clause=$query_string." like '%".$_GET["search_".$this->name]."%' ";	
	else
		$where_clause="";
	
	if($where_query!="" || $where_clause!="")
		$clause=" WHERE ";
	else
	    $clause="";
		
	$all_query=$head_query.$clause.($where_query!=""?$where_query:"");
	$all_query.=($where_query!=""?($where_clause!=""?" AND ( ".$where_clause." ) " :""):$where_clause);
	$all_query.=($sort_query!=""?" order by ".$sort_query:"");
	
	return $all_query;
}


}
?>